package main

import "fmt"

// 如何求升序排列的数组中绝对值最小的数

func main() {
	arr := []int{-10, -5, -2, 7, 15, 50}
	fmt.Println(findMinMath(arr))
}

func findMinMath(arr []int) int {
	if arr == nil || len(arr) == 0 {
		return -1
	}
	if arr[0] > 0 {
		return arr[0]
	}
	end := len(arr) - 1
	if arr[end] < 0 {
		return arr[end]
	}
	begin, mid := 0, 0

	for true {
		mid = begin + (end-begin)/2
		if arr[mid] == 0 {
			return 0
		} else if arr[mid] > 0 {
			if arr[mid-1] > 0 {
				end = mid - 1
			} else if arr[mid-1] == 0 {
				return 0
			} else {
				break
			}
		} else {
			if arr[mid+1] < 0 {
				begin = mid + 1
			} else if arr[mid+1] == 0 {
				return 0
			} else {
				break
			}
		}
	}

	if arr[mid] > 0 {
		if arr[mid] < -arr[mid-1] {
			return arr[mid]
		} else {
			return arr[mid-1]
		}
	} else {
		if -arr[mid] < arr[mid+1] {
			return arr[mid]
		} else {
			return arr[mid+1]
		}
	}
}
